package com.example.carrierapp.util;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.lb.fingerdemo.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/12/7.
 */
public class CheckUpUtils {
    private static final int DOWN_UPDATE = 0;
    private static final int DOWN_OVER = 1;
    private static Button installBtn;
    private static TextView progressAmount; //进度值
    private static String apkUrl; //安装包下载路径
    private String updateMsg = "发现新的版本，请更新后使用!";    //提示语
    //    private static final String savePath = "/sdcard/CarrierApp/updatedemo/"; //下载安装包保存路径
    private static final String saveFileName = Environment.getExternalStorageDirectory() + "/JwellCarrier/carrier.apk"; //安装包保存文件
    private static ProgressBar progressBar; //下载进度条
    private static int progressValue; //下载进度值
    private Dialog noticeDialog;//更新提示对话框
    private Dialog downloadDialog;//更新下载对话框
    private static Context context;
    private static boolean downOver = false;
    private static boolean isShowUpdata = false;
    private static boolean isShowLoad = false;
    private static String remark = null;

    static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE: //下载中，更新进度
                    progressBar.setProgress(progressValue);
                    LogUtil.i("TAGL", "progressValue:" + progressValue);
                    progressAmount.setText(String.valueOf(progressValue));
                    break;
                case DOWN_OVER: //下载完成，安装apk
                    downOver = true;
                    if (installBtn != null) {
                        installBtn.setEnabled(true);
                    }
                    installApk(context);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 获取软件版本号
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            //"com.jwwl.carrierapp"对应AndroidManifest.xml里的package="……"部分
//            verCode = context.getPackageManager().getPackageInfo("com.jwell.driver", 0).versionCode;
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            verCode = packageInfo.versionCode;
            Log.i("Version", "版本号：" + verCode);
        } catch (PackageManager.NameNotFoundException e) {
        }
        return verCode;
    }

    /**
     * 获取版本名称
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            verName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
        }
        Log.i("Version", "verName：" + verName);
        return verName;
    }

//    public static void showNoticeDialog(final Context con, final VersionBean versionBean) {
//        remark = versionBean.getRemark();
//        showNoticeDialog(con, versionBean.getFilePath(), versionBean.isUpdate(),remark);
//    }


    /**
     * 提示有新的软件版本
     */
    public static void showNoticeDialog(final Context con, final String apkUrl1, boolean isMust, String s) {
        if (isShowUpdata || isShowLoad) {
            return;
        }
        isShowUpdata = true;
        context = con;
        apkUrl = apkUrl1;
        View dialogConentView = LayoutInflater.from(context).inflate(R.layout.dialog_soft_update_remind, null);

        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setContentView(dialogConentView);
        dialog.setCancelable(!isMust);
        dialog.setCanceledOnTouchOutside(!isMust);
        dialog.show();
        TextView textView = (TextView) dialogConentView.findViewById(R.id.text_reamrk);
        if (s != null) {
            textView.setText(s.replace("\\n", "\n"));
        }
        Button updateBtn = (Button) dialogConentView.findViewById(R.id.dialog_soft_update_remind_button);
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("TAG", "11");
                dialog.dismiss();
                showDownloadDialog(context, apkUrl1); //进入版本下载界面}
            }
        });
        Button negativeBtn = (Button) dialogConentView.findViewById(R.id.dialog_soft_update_remind_negative_button);

        negativeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMust) {
                    ToastUtils.showCenterToast(context, "该版本必须更新后才能使用！");
                } else {
                    dialog.dismiss();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                isShowUpdata = false;
            }
        });
    }

    /**
     * 显示下载进度
     */
    private static void showDownloadDialog(final Context context, final String apkUrl) {
        isShowLoad = true;
        View dialogConentView = LayoutInflater.from(context).inflate(R.layout.dialog_soft_update_progress, null);
        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setContentView(dialogConentView);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button againBtn = (Button) dialogConentView.findViewById(R.id.dialog_soft_update_progress_again);
        installBtn = (Button) dialogConentView.findViewById(R.id.dialog_soft_update_progress_install);
        progressBar = (ProgressBar) dialogConentView.findViewById(R.id.dialog_soft_update_progress_bar);
        progressAmount = (TextView) dialogConentView.findViewById(R.id.progress_amount);

        //安装
        installBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downOver) {
                    installApk(context);
                }
            }
        });

        //重新下载
        againBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downOver) {
                    downOver = false;
                    progressBar.setProgress(0);
                    installBtn.setEnabled(false);
                    downloadApk(apkUrl);
                } else {
                    ToastUtils.showCenterToast(context, "请等待下载完成");
                }
            }
        });

        //下载软件
        downloadApk(apkUrl);

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                isShowLoad = false;
            }
        });
    }

    /**
     * 下载apk
     */
    private static void downloadApk(final String apkUrl) {
        Log.i("TAG", "3" + apkUrl);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(apkUrl);
                    //开启连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //设置超时的时间，5000毫秒即5秒
                    conn.setConnectTimeout(5000);
                    conn.setRequestProperty("Accept-Encoding", "identity");

                    //设置获取方式为GET
                    conn.setRequestMethod("GET");
                    conn.connect();
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        int length = conn.getContentLength();

                        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

                        File file = new File(saveFileName);
                        if (!file.exists()) {
                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            file.createNewFile();
                        }
                        byte[] buf = new byte[1024];
                        int size;
                        int count = 0;
                        FileOutputStream fos = new FileOutputStream(saveFileName);
                        while ((size = bis.read(buf)) != -1) {
                            count += size;
                            progressValue = (int) (((float) count / length) * 100);
                            //更新进度
                            progressBar.setProgress(progressValue);
                            handler.sendEmptyMessage(DOWN_UPDATE);
                            fos.write(buf, 0, size);
                        }
                        // 通知完成
                        handler.sendEmptyMessage(DOWN_OVER);
                        fos.close();
                        bis.close();
                        conn.disconnect();
                    } else {
                    }
                } catch (Exception e) {
                    System.out.println("e=" + e.toString());
                }
            }
        }).start();
    }

    /**
     * 安装apk
     */
    private static void installApk(Context context) {
        LogUtil.d("installApk-" + saveFileName);
        if (!TextUtils.isEmpty(saveFileName)) {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            File file = new File(saveFileName);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(context, "com.example.carrierapp.fileprovider", file);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                context.startActivity(intent);
            }
        }
    }

//    @Override
//    public void onPermissionsGranted(int requestCode, List<String> perms) {
//        showDownloadDialog(context, apkUrl); //进入版本下载界面}
//    }
//
//    @Override
//    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        Log.e("msg", "权限失败");
//        Toast.makeText(context, "需要读写权限才能下载更新", Toast.LENGTH_SHORT).show();
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//
//    }
}
